import 'dart:io';

import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:gzmall_app/common/api.dart';
import 'package:gzmall_app/common/color_common.dart';
import 'package:gzmall_app/common/net_util.dart';
import 'package:gzmall_app/common/toast_util.dart';
import 'package:gzmall_app/goods/goods_details_page.dart';
import 'package:gzmall_app/model/order_item.dart';
import 'package:gzmall_app/model/picture.dart';
import 'package:image_picker/image_picker.dart';

class OrderCommentPage extends StatefulWidget {
  OrderItem item;

  OrderCommentPage(this.item);

  @override
  State<StatefulWidget> createState() => OrderCommentPageState(this.item);
}

class OrderCommentPageState extends State<OrderCommentPage> {
  String _content;
  String _review = "well";
  bool _hideUser = true;
  List<String> _commentPictureIds = [];
  OrderItem item;
  TextEditingController _contentController = TextEditingController();

  OrderCommentPageState(this.item);

  @override
  Widget build(BuildContext context) {
    List<Widget> _reviews = [];
    switch (_review) {
      case "well":
        _reviews.add(_createReview(() {
          if (!mounted) return;
          setState(() {
            _review = "bad";
          });
        }, "images/collect_p_s.png"));
        _reviews.add(_createReview(() {
          if (!mounted) return;
          setState(() {
            _review = "normal";
          });
        }, "images/collect_p_s.png"));
        _reviews.add(_createReview(() {
          if (!mounted) return;
          setState(() {
            _review = "well";
          });
        }, "images/collect_p_s.png"));
        break;
      case "normal":
        _reviews.add(_createReview(() {
          if (!mounted) return;
          setState(() {
            _review = "bad";
          });
        }, "images/collect_p_s.png"));
        _reviews.add(_createReview(() {
          if (!mounted) return;
          setState(() {
            _review = "normal";
          });
        }, "images/collect_p_s.png"));
        _reviews.add(_createReview(() {
          if (!mounted) return;
          setState(() {
            _review = "well";
          });
        }, "images/collect_p_u.png"));
        break;
      case "bad":
        _reviews.add(_createReview(() {
          if (!mounted) return;
          setState(() {
            _review = "bad";
          });
        }, "images/collect_p_s.png"));
        _reviews.add(_createReview(() {
          if (!mounted) return;
          setState(() {
            _review = "normal";
          });
        }, "images/collect_p_u.png"));
        _reviews.add(_createReview(() {
          if (!mounted) return;
          setState(() {
            _review = "well";
          });
        }, "images/collect_p_u.png"));
        break;
    }

    List<Widget> _imageWidget = [];
    if (_imageList != null && _imageList.length > 0) {
      _imageWidget = _imageList
          .map((i) => InkWell(
                onDoubleTap: () {
                  if (!mounted) return;
                  setState(() {
                    _imageList.remove(i);
                    _commentPictureIds.remove(i.id);
                  });
                },
                child: Padding(
                  padding: const EdgeInsets.only(right: 10.0),
                  child: CachedNetworkImage(
                    width: 80.0,
                    height: 80.0,
                    imageUrl: i.image,
                    fit: BoxFit.fill,
                  ),
                ),
              ))
          .toList();
    }
    if (_imageWidget.length < 3) {
      _imageWidget.add(
        InkWell(
          onTap: () {
            _showSelectPhoto();
          },
          child: Container(
            color: Colors.white,
            width: 80.0,
            height: 80.0,
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Image.asset(
                  "images/add_photo.png",
                  width: 40.0,
                  height: 40.0,
                ),
                Text("照片"),
              ],
            ),
          ),
        ),
      );
    }
    return Scaffold(
      appBar: _createAppBar(),
      body: item != null
          ? ListView(
              children: <Widget>[
                InkWell(
                  onTap: () {
                    Navigator.of(context).push(MaterialPageRoute(builder: (_) {
                      return GoodsDetailsPage(productId: item.spuId);
                    }));
                  },
                  child: Container(
                    color: Colors.white,
                    padding: const EdgeInsets.all(10.0),
                    child: Row(
                      children: <Widget>[
                        item.avatar != null
                            ? CachedNetworkImage(
                                width: 100.0,
                                height: 100.0,
                                imageUrl: item.avatar,
                                fit: BoxFit.fill,
                              )
                            : Container(
                                color: ColorCommon.grey5,
                                width: 100.0,
                                height: 100.0,
                              ),
                        Padding(
                          padding: const EdgeInsets.all(10.0),
                          child: Column(
                            mainAxisAlignment: MainAxisAlignment.start,
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: <Widget>[
                              Text(
                                item.name ?? "",
                                style: TextStyle(
                                    color: ColorCommon.black1, fontSize: 16.0),
                              ),
                              Padding(
                                padding: const EdgeInsets.only(
                                    bottom: 5.0, top: 5.0),
                                child: Text(
                                  "商品评分",
                                  style: TextStyle(
                                      color: ColorCommon.black1,
                                      fontSize: 16.0),
                                ),
                              ),
                              Row(
                                children: _reviews,
                              ),
                            ],
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
                Container(
                  height: 130.0,
                  padding: const EdgeInsets.all(10.0),
                  color: ColorCommon.grey5,
                  child: TextField(
                    maxLines: 5,
                    controller: _contentController,
                    style: new TextStyle(color: ColorCommon.black1),
                    decoration: new InputDecoration.collapsed(
                      hintText: "请输入商品评价",
                      hintStyle:
                          TextStyle(fontSize: 14.0, color: ColorCommon.grey1),
                    ),
                    onChanged: (str) {
                      _content = str ?? '';
                    },
                  ),
                ),
                Container(
                  color: ColorCommon.grey10,
                  padding: const EdgeInsets.all(10.0),
                  child: Row(
                    children: _imageWidget,
                  ),
                ),
                Container(
                  color: ColorCommon.grey10,
                  child: Row(children: <Widget>[
                    Checkbox(
                      value: _hideUser,
                      onChanged: (isCheck) {
                        if (!mounted) return;
                        setState(() {
                          _hideUser = isCheck;
                        });
                      },
                    ),
                    Text(
                      "匿名评价",
                      style:
                          TextStyle(fontSize: 16.0, color: ColorCommon.black1),
                    ),
                  ]),
                ),
              ],
            )
          : Center(
              child: Text(
                "暂时没有数据",
                style: TextStyle(color: ColorCommon.black1, fontSize: 16.0),
              ),
            ),
    );
  }

  _createAppBar() {
    return new AppBar(
      elevation: 0.0,
      title: new Text("订单评价"),
      leading: new IconButton(
        icon: new Icon(Icons.arrow_back_ios),
        onPressed: () {
          Navigator.of(context).pop();
        },
      ),
      actions: <Widget>[
        InkWell(
          onTap: () {
            if (item != null) {
              _comment(_content, item.spuId, item.id, _review, _hideUser,
                  _commentPictureIds);
            }
          },
          child: Container(
            child: Text("提交"),
            alignment: Alignment.center,
            padding: const EdgeInsets.only(right: 15.0),
          ),
        ),
      ],
    );
  }

  Widget _createReview(Function onTap, String source) {
    return InkWell(
      onTap: onTap,
      child: Image.asset(
        source,
        width: 30.0,
        height: 30.0,
      ),
    );
  }

  _showSelectPhoto() {
    showCupertinoModalPopup(
      context: context,
      builder: (_) {
        return CupertinoActionSheet(
          actions: <Widget>[
            CupertinoActionSheetAction(
              onPressed: () {
                _getImage(ImageSource.camera);
                Navigator.of(context).pop();
              },
              child: Text("拍照"),
            ),
            CupertinoActionSheetAction(
              onPressed: () {
                _getImage(ImageSource.gallery);
                Navigator.of(context).pop();
              },
              child: Text("相册"),
            ),
          ],
          cancelButton: CupertinoActionSheetAction(
            onPressed: () {
              Navigator.of(context).pop();
            },
            child: Text("取消"),
          ),
        );
      },
    );
  }

  Future _getImage(ImageSource source) async {
    var image = await ImagePicker.pickImage(source: source, maxWidth: 600.0);

    if (!mounted) return;
    setState(() {
      _commentPicture(image);
    });
  }

  _comment(String content, int spuId, int orderItemId, String review,
      bool hideUser, List<String> commentPictureIds) {
    FormData formData = new FormData.fromMap({
      "comment[content]": content,
      "comment[spu_id]": spuId.toString(),
      "comment[order_item_id]": orderItemId,
      "comment[review]": review,
      "comment[hide_user]": hideUser,
      "comment[comment_picture_ids]": commentPictureIds
    });
    NetUtil.post(context, Api.comments, (data, message) {
      ToastUtil.showMessageToast(message);
      Navigator.of(context).pop(true);
    }, params: formData, isShowLoading: true);
  }

  List<Picture> _imageList = [];
  _commentPicture(File image) {
    FormData formData = new FormData.fromMap(
        {"comment_picture[image]": MultipartFile.fromFileSync(image.path)});
    NetUtil.post(context, Api.commentsPictures, (data, message) {
      ToastUtil.showMessageToast(message);
      Picture i = Picture.fromJson(data);
      if (!mounted) return;
      setState(() {
        _imageList.add(i);
        _commentPictureIds.add(i.id.toString());
      });
    }, params: formData, isShowLoading: true);
  }
}
